<template>
  <el-card>
    <div class="header" slot="header">
      <span>管理员信息</span>
    </div>
    管理员ID：{{ userInfo.id }}
    <el-divider></el-divider>
    账号：{{ userInfo.account }}
    <el-divider></el-divider>
    用户组：{{ userInfo.userGroup }}
    <el-divider></el-divider>
    创建时间：{{ userInfo.ctime | formatYMDhms }}
    <el-divider></el-divider>
    <div class="df aic">
      <!-- action上传图片服务器地址 -->
      <!-- show-file-list 展示上传列表 -->
      管理员头像：
      <el-upload class="avatar-uploader" :action="`${API}/users/avatar_upload`"
        :show-file-list="false" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="userInfo.imgUrl" :src="userInfo.imgUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <el-divider></el-divider>
  </el-card>
</template>

<script>
import { avatarUploadReq, avatarReditReq } from "@/api/user";
import { mapState } from "vuex";

export default {
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  data() {
    return {
      API: "http://sell.h5.itsource.cn:8087",
    };
  },
  methods: {
    //上传成功触发函数
    async handleAvatarSuccess(res) {
      // console.log('res :>> ', res)

      let { code, msg, imgUrl } = res;
      if (code === 0) {
        //发送请求修改头像
        let res2 = await avatarReditReq({ imgUrl });
        let { code, msg } = res2.data;
        if (code === 0) {
          //拉取用户信息
          this.$store.dispatch("user/A_getUserInfo");
        }
      }
    },

    //约束上传文件类型&上传文件大小
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isJPG = /(png|jpeg)/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  line-height: 90px;
  text-align: center;
}
.avatar {
  width: 90px;
  height: 90px;
  display: block;
}
</style>
